<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
  <!-- 引入样式 -->
  <link rel="stylesheet" href="../../plugins/element-ui/index.css" />
  <link rel="stylesheet" href="../../styles/common.css" />
  <link rel="stylesheet" href="../../styles/page.css" />
  <style>
    .selectInput {
      position: relative;
      width: 100%;
      min-width: 100px;
    }
    .selectInput .flavorSelect {
      position: absolute;
      width: 100%;
      padding: 0 10px;
      border-radius: 3px;
      border: solid 1px #00FA9A;
      line-height: 30px;
      text-align: center;
      background: #fff;
      top: 50px;
      z-index: 99;
    }
    .selectInput .flavorSelect .items {
      cursor: pointer;
      display: inline-block;
      width: 100%;
      line-height: 35px;
      border-bottom: solid 1px #f4f4f4;
      color: #666;
    }
    .selectInput .flavorSelect .none {
      font-size: 14px;
    }

    #shop-add-app .uploadImg .el-form-item__label::before{
          content: '*';
          color: #00FA9A;
          margin-right: 4px;
      }

  </style>
</head>
<body>
   <div class="addBrand-container" id="shop-update-app">
    <div class="container">
      <el-form ref="ruleForm" :model="ruleForm" :rules="rules" :inline="true" label-width="180px" class="demo-ruleForm"
      >
        <div>
          <el-form-item label="商品名称:" prop="shopName">
            <el-input v-model="ruleForm.shopName" placeholder="请填写商品名称" maxlength="20"></el-input>
          </el-form-item>
          <el-form-item label="商品类型:" prop="categoryId">
            <el-select v-model="ruleForm.categoryId" placeholder="请选择商品类型">
              <el-option v-for="item in options" :key="item.id" :label="item.name" :value="item.id">
              </el-option>
            </el-select>
          </el-form-item>

        </div>
        <div>
          <el-form-item label="商品价格:" prop="newPrice">
            <el-input v-model="ruleForm.newPrice" placeholder="请设置商品价格"/>
          </el-form-item>
        </div>
        <div>
          <el-form-item label="商品原价:" prop="oldPrice">
            <el-input v-model="ruleForm.oldPrice" placeholder="请设置商品原价"/>
          </el-form-item>
        </div>
        <div>
          <el-form-item label="商品顺序:" prop="sort">
            <el-input v-model="ruleForm.sort" placeholder="请设置商品出现顺序"/>
          </el-form-item>
        </div>
        <div>
          <el-form-item label="库存数量:" prop="inventory">
            <el-input v-model="ruleForm.inventory" placeholder="请设置商品库存数量"/>
          </el-form-item>
        </div>
        <div>
          <el-form-item label="商品图片:" prop="image" class="uploadImg">
            <el-upload class="avatar-uploader" action="/common/upload" :show-file-list="false" :on-success="handleAvatarSuccess" :on-change="onChange" ref="upload">
              <img v-if="image" :src="image" class="avatar">
              <i v-else class="el-icon-plus avatar-uploader-icon"></i>
            </el-upload>
          </el-form-item>
        </div>

        <div class="address">
          <el-form-item label="商品描述:" prop="description">
            <el-input v-model="ruleForm.description" type="textarea" :rows="3" placeholder="商品描述，最长200字" maxlength="200"/>
          </el-form-item>
        </div>

        <div class="subBox address">
          <el-form-item>
            <el-button @click="goBack()">取消</el-button>
            <el-button type="primary" @click="submitForm('ruleForm')">保存</el-button>
            <el-button v-if="actionType == 'add'" type="primary" class="continue" @click="submitForm('ruleForm','goAnd')">
              保存并继续添加商品
            </el-button>
          </el-form-item>
        </div>
      </el-form>
    </div>
  </div>
    <!-- 开发环境版本，包含了有帮助的命令行警告 -->
    <script src="../../plugins/vue/vue.js"></script>
    <!-- 引入组件库 -->
    <script src="../../plugins/element-ui/index.js"></script>
    <!-- 引入axios -->
    <script src="../../plugins/axios/axios.min.js"></script>
    <script src="../../js/request.js"></script>
    <script src="../../js/validate.js"></script>
    <script src="../../js/index.js"></script>
    <script src="../../api/shop.js"></script>
    <script>
      new Vue({
        el: '#shop-update-app',
        data() {
          return {
            id: '',
            tableData : [],
            restKey: 0,
            textarea: '',
            value: '',
            image: '',
            actionType: '',
            index : 0,
            inputStyle  : {'flex':1},
            ruleForm: {
              'id': '',
              'shopName': '',
              'newPrice': '',
              'oldPrice': '',
              'image': '',
              'sort':"",
              'inventory':"",
              'description': '',
              'status': true,
              'categoryId':""
            },
            options:[],
            mak: false,
            checkAll:false,
            isIndeterminate: true
          }
        },
        computed: {
          rules () {
            return {
              'name': [
                {'required': true, 'message': '请填写名称', 'trigger': 'blur'}
              ],
              'price': [
                {
                  'required': true,
                  validator: (rules, value, callback) => {
                    if (!value) {
                      callback(new Error('请填写价格'))
                    } else {
                      const reg = /^\d+(\.\d{0,2})?$/;
                      if (reg.test(value)) {
                        if(value < 10000){
                          callback()
                        }else{
                          callback(new Error('价格小于10000'))
                        }
                      } else {
                        callback(new Error('价格格式只能为数字,且最多保留两位小数'))
                      }
                    }
                  },
                  'trigger': 'blur'
                }
              ],
            }
          }
        },
        created() {
          //和修改相关
          this.id = requestUrlParam('id');
          this.actionType = this.id ? 'edit' : 'add';
          if (this.id) {
            this.init()
          }
          var _this = this;
          getAllCategory().then(res=>{
              this.options=res.data


        })

        },
        mounted() {
        },
        methods: {
          async init () {
            var _this = this

            queryShopById(this.id).then(res => {
              console.log(res);
              if (String(res.code) === '1') {
                this.ruleForm = { ...res.data };
                console.log(res.data.categoryId)
                this.ruleForm.status = res.data.status == '1'
                this.image = `/common/download?name=${res.data.image}`
              } else {
                this.$message.error(res.msg || '操作失败')
              }
            })


          },

          submitForm(formName, st) {
            this.$refs[formName].validate((valid) => {
              if (valid) {
                let params = {...this.ruleForm};
                params.status = this.ruleForm ? 1 : 0;
                if(!this.image){
                  this.$message.error('请上传图片');
                  return 
                }
                console.log("11111111111111111111111111111")

                console.log("11111111111111111111111111111")
                enableOrDisableShop(params).then(res => {
                  if (res.code === 1) {
                    this.$message.success('商品修改成功！');

                    if (!st) {
                      this.goBack()
                    } else {
                      this.image = '';
                      this.ruleForm = {
                        'id': '',
                        'name': '',
                        'type':'',
                        'count':'',
                        'price': '',
                        'oldPrice': '',
                        'image': '',
                        'description': '',
                        'status': true,
                      }
                    }
                  } else {
                    this.$message.error(res.msg || '操作失败')
                  }
                }).catch(err => {
                  this.$message.error('请求出错了：' + err)
                })
              } else {
                return false
              }
            })
          },
          handleCheckAllChange(val) {

            this.isIndeterminate = false;
            console.log(val)
            // this.checkedCities = val ? cityOptions : [];
            // this.isIndeterminate = false;

          },
          handleCheckedCitiesChange(value) {
            let checkedCount = value.length;

            console.log(value)

            // let checkedCount = value.length;
            // this.checkAll = checkedCount === this.cities.length;
            // this.isIndeterminate = checkedCount > 0 && checkedCount < this.cities.length;
          },

          handleAvatarSuccess (response, file, fileList) {
            // 拼接down接口预览
            if(response.code === 0 && response.msg === '未登录'){
              window.top.location.href = '../login/login.html'
            }else{
              this.image = `/common/download?name=${response.data}`;
              this.ruleForm.image = response.data
            }
          },

          onChange (file) {
            if(file){
              const suffix = file.name.split('.')[1];
              const size = file.size / 1024 / 1024 < 2;
              if(['png','jpeg','jpg'].indexOf(suffix) < 0){
                this.$message.error('上传图片只支持 png、jpeg、jpg 格式！');
                this.$refs.upload.clearFiles();
                return false
              }
              if(!size){
                this.$message.error('上传文件大小不能超过 2MB!');
                return false
              }
              return file
            }
          },
          
          goBack(){
            window.parent.menuHandle({
              id: '11',
              url: '/back/page/shop/list.html',
              name: '商品管理'
            },false)
          }
        }
      })
    </script>
</body>
</html>